/*
� 最佳准确率窗口:
{
  windowSize: 3,
  total: 1244,
  correct: 840,
  accuracy: 67.52,
  maxWrongStreak: 8
}

� 最小连续错误窗口:
{
  windowSize: 4,
  total: 1244,
  correct: 824,
  accuracy: 66.24,
  maxWrongStreak: 5
}

*/
// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule("../../../awakened-potential/helpers/readAllValues.js");
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据
const allValues = readAllValues("m");

// ✅ 号码池（01~49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

/**
 * 判断是否奇数
 */
const isOdd = (numStr) => parseInt(numStr, 10) % 2 === 1;

/**
 * 分析奇偶比例
 */
const analyzeOddEvenRatio = (temp) => {
  let oddCount = 0;
  let evenCount = 0;

  temp.forEach((item) => {
    const num = item.number;
    if (isOdd(num)) oddCount++;
    else evenCount++;
  });

  const total = oddCount + evenCount;
  return {
    oddRatio: oddCount / total,
    evenRatio: evenCount / total,
  };
};

/**
 * 根据奇偶比例选择32个号码（稳定、无随机）
 */
const select32NumbersByOddEven = (oddRatio) => {
  const odds = allNumbers.filter((n) => isOdd(n)).sort();
  const evens = allNumbers.filter((n) => !isOdd(n)).sort();

  let targetOddCount = Math.round(oddRatio * 32);
  let targetEvenCount = 32 - targetOddCount;

  targetOddCount = Math.min(targetOddCount, odds.length);
  targetEvenCount = Math.min(targetEvenCount, evens.length);

  let selected = odds.slice(0, targetOddCount).concat(
    evens.slice(0, targetEvenCount)
  );

  const already = new Set(selected);
  const remaining = allNumbers.filter((n) => !already.has(n));
  for (const n of remaining) {
    if (selected.length >= 32) break;
    selected.push(n);
  }

  if (selected.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${selected.length} 个）`);
  }

  return selected;
};

// ✅ 多窗口循环测试
const results = [];

for (let windowSize = 2; windowSize <= 200; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = allValues.slice(Math.max(0, index - windowSize), index);
    if (temp.length === 0) return;

    const { oddRatio } = analyzeOddEvenRatio(temp);
    const selectedNumbers = select32NumbersByOddEven(oddRatio);

    if (selectedNumbers.length !== 32) {
      throw new Error("选出的32个号码数量不正确");
    }

    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
    predictResults.push(selectedNumbers);
  });

  const total = predictResults.length;
  const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

  results.push({
    windowSize,
    total,
    correct,
    accuracy: Number(accuracy),
    maxWrongStreak,
  });
}

// ✅ 输出全部测试结果
results.forEach((res) => {
  console.log(
    `windowSize = ${res.windowSize}, 准确率 = ${res.accuracy}%, 最大连续错误次数 = ${res.maxWrongStreak}`
  );
});

// ✅ 输出最优结果
const bestAccuracy = _.maxBy(results, "accuracy");
const bestStable = _.minBy(results, "maxWrongStreak");

console.log("\n📊 最佳准确率窗口:");
console.log(bestAccuracy);
console.log("\n🧱 最小连续错误窗口:");
console.log(bestStable);
